package com.hypo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hypo.pojo.*;
import com.hypo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    /**
     * 分页查询
     *
     * @param userQueryParam 封装请求参数
     * @return 返回结果总数据及查询集合
     */
    @GetMapping
    public Result pageQuery(UserQueryParam userQueryParam) {
        //1.封装分页对象IPage
        IPage<User> page = new Page<>(userQueryParam.getPage(), userQueryParam.getPageSize());
        //2.封装条件查询Wrapper
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //3.判断name和gender是否为空，如果为空不添加条件查询
        //if (userQueryParam.getName() != null && !userQueryParam.getName().trim().isEmpty()) {
        //    queryWrapper.like(User::getName, userQueryParam.getName());
        //}
        //if (userQueryParam.getGender() != null) {
        //    queryWrapper.eq(User::getGender, userQueryParam.getGender());
        //}
        queryWrapper.like(!Objects.isNull(userQueryParam.getName()), User::getName, userQueryParam.getName())
                .eq(!Objects.isNull(userQueryParam.getGender()), User::getGender, userQueryParam.getGender());
        //4.执行分页查询
        IPage<User> pageInfo = userService.page(page, queryWrapper);
        //5.解析分页查询信息，获取查询集合，获取总条数
        List<User> list = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        //6.封装PageResult返回
        return Result.success(new PageResult<>(total, list));
    }

    /**
     * 登录
     *
     * @param user 用户登录信息
     * @return 返回令牌
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        //1.判断账号密码是否为空
        if (user.getUsername() == null || user.getPassword() == null) {
            return Result.error("用户名或密码不能为空");
        }
        //2.不为空执行查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, user.getPassword());
        //3.将查询数据封装集合
        List<User> userList = userService.list(queryWrapper);
        //4.判断集合是否存在唯一匹配
        if (userList.size() == 1) {
            User userInfo = userList.get(0);
            //5.封装令牌
            LoginInfo loginInfo = userService.getToken(userInfo);
            //6.返回LoginInfo数据
            return Result.success(loginInfo);
        } else {
            return Result.error("用户名或密码错误");
        }
    }
}
